<template>
  <view class="onboarding-page">
    <!-- 简单导航栏 -->
    <u-navbar
          title="入职资料补充"
          :border="false"
          bgColor="#FFFFFF"
          titleColor="#333333"
          :titleStyle="{ fontSize: '36rpx', fontWeight: '500' }"
          leftIcon="arrow-left"
          placeholder
          @leftClick="goBack"
        ></u-navbar>
    
    <!-- 欢迎信息 -->
    <view class="welcome-message">
      <text class="welcome-text">Hi, 为了您快速入职并准时收到工资等费请核对填写真实信息~</text>
    </view>
    
         <!-- 报名企业 -->
     <view class="section company-section">
       <view class="company-card">
         <view class="company-status">
           <text class="status-text">确认报名</text>
           <text class="company-name">{{ companyInfo.company || '暂无报名企业' }}</text>
           <text v-if="companyInfo.position" class="company-position">{{ companyInfo.position }}</text>
         </view>
         <view class="company-bg"></view>
       </view>
     </view>
    
    <!-- 基础信息 -->
    <view class="section">
      <view class="section-title">基础信息</view>
      <view class="form-container">
        <!-- 姓名 -->
        <view class="form-item">
          <view class="form-label">
            <text class="required">*</text>
            <text class="label-text">姓名</text>
          </view>
          <input
            v-model="formData.name"
            placeholder="请输入姓名"
            class="form-input"
          />
        </view>
        
        
        
        <!-- 身份证 -->
        <view class="form-item">
          <view class="form-label">
            <text class="required">*</text>
            <text class="label-text">身份证</text>
          </view>
          <input
            v-model="formData.idCard"
            placeholder="请输入身份证号"
            class="form-input"
          />
        </view>
        

      
        
        <!-- 手机号码 -->
        <view class="form-item">
          <view class="form-label">
            <text class="required">*</text>
            <text class="label-text">手机号码</text>
          </view>
          <view class="phone-input">
            <input
              v-model="formData.phone"
              placeholder="请输入手机号码"
              class="form-input"
            />
                         <u-button
               :text="countdownText"
               size="mini"
               type="primary"
               :disabled="isCountingDown"
               @click="getVerificationCode"
               :customStyle="{ 
                 fontSize: '22rpx', 
                 padding: '8rpx 16rpx',
                 borderRadius: '16rpx',
                 minWidth: '120rpx',
                 maxWidth: '140rpx',
                 backgroundColor: '#FF6B35',
                 borderColor: '#FF6B35'
               }"
             />
          </view>
        </view>
        
        <!-- 验证码 -->
        <view class="form-item">
          <view class="form-label">
            <text class="required">*</text>
            <text class="label-text">验证码</text>
          </view>
          <input
            v-model="formData.verificationCode"
            placeholder="请输入验证码"
            class="form-input"
          />
        </view>
        
        <!-- 微信 -->
        <view class="form-item">
          <view class="form-label">
            <text class="label-text">微信</text>
          </view>
          <input
            v-model="formData.qq"
            placeholder="请输入微信号"
            class="form-input"
          />
        </view>
        
                 <!-- 学历 -->
         <view class="form-item">
           <view class="form-label">
             <text class="required">*</text>
             <text class="label-text">学历</text>
           </view>
                       <u-picker
              :show="showEducationPicker"
              :columns="[educationOptions.map(item => item.fullName)]"
              @confirm="onEducationConfirm"
              @cancel="showEducationPicker = false"
              :customStyle="{ 
                confirmColor: '#FF6B35',
                cancelColor: '#666666'
              }"
            />
           <view class="select-input" @click="showEducationPicker = true">
             <text class="select-text" :class="{ placeholder: !getEducationDisplayName }">
               {{ getEducationDisplayName || '请选择' }}
             </text>
             <text class="arrow-icon">▼</text>
           </view>
         </view>
        
        <!-- 学校名称 -->
        <view class="form-item">
          <view class="form-label">
            <text class="required">*</text>
            <text class="label-text">学校名称</text>
          </view>
          <input
            v-model="formData.school"
            placeholder="请输入学校名称"
            class="form-input"
          />
        </view>
      </view>
    </view>
    
    <!-- 紧急联系人 -->
    <view class="section">
      <view class="section-title">紧急联系人</view>
      <view class="form-container">
        <!-- 姓名 -->
        <view class="form-item">
          <view class="form-label">
            <text class="required">*</text>
            <text class="label-text">姓名</text>
          </view>
          <input
            v-model="formData.emergencyName"
            placeholder="请输入紧急联系人姓名"
            class="form-input"
          />
        </view>
        
        <!-- 手机号 -->
        <view class="form-item">
          <view class="form-label">
            <text class="required">*</text>
            <text class="label-text">手机号</text>
          </view>
          <input
            v-model="formData.emergencyPhone"
            placeholder="请输入紧急联系人手机号"
            class="form-input"
          />
        </view>
        
                 <!-- 与本人关系 -->
         <view class="form-item">
           <view class="form-label">
             <text class="required">*</text>
             <text class="label-text">与本人关系</text>
           </view>
                       <u-picker
              :show="showRelationshipPicker"
              :columns="[relationshipOptions.map(item => item.fullName)]"
              @confirm="onRelationshipConfirm"
              @cancel="showRelationshipPicker = false"
              :customStyle="{ 
                confirmColor: '#FF6B35',
                cancelColor: '#666666'
              }"
            />
           <view class="select-input" @click="showRelationshipPicker = true">
             <text class="select-text" :class="{ placeholder: !getRelationshipDisplayName }">
               {{ getRelationshipDisplayName || '请选择' }}
             </text>
             <text class="arrow-icon">▼</text>
           </view>
         </view>
      </view>
    </view>
    
    <!-- 银行卡信息 -->
    <view class="section">
      <view class="section-title">银行卡信息</view>
      <view class="form-container">
        <!-- 银行卡号 -->
        <view class="form-item">
          <view class="form-label">
            <text class="label-text">银行卡号</text>
          </view>
          <view class="bank-input">
            <input
              v-model="formData.bankCard"
              placeholder="请输入银行卡号"
              class="form-input"
            />
            <text v-if="false" class="camera-icon" @click="scanBankCard">📷</text>
          </view>
        </view>
        
        <!-- 开户银行 -->
        <view class="form-item" style="margin-bottom: 100rpx;">
          <view class="form-label">
            <text class="label-text">开户银行</text>
          </view>
          <input
            v-model="formData.bankName"
            placeholder="请输入开户行"
            class="form-input"
          />
        </view>
      </view>
    </view>
    
         <!-- 确认提交按钮 -->
     <view class="submit-section">
               <u-button
          text="确认提交"
          type="primary"
          size="large"
          :disabled="!isFormValid"
          @click="submitForm"
          :customStyle="{ 
            width: '100%',
            height: '88rpx',
            borderRadius: '44rpx',
            fontSize: '32rpx',
            fontWeight: '500',
            backgroundColor: '#FF6B35',
            borderColor: '#FF6B35',
            boxShadow: '0 8rpx 24rpx rgba(255, 107, 53, 0.3)'
          }"
        />
     </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { userStore } from '@/stores/userStore'
import { userApi, verifyApi, systemApi } from '@/api/api-helper.js'


// 表单数据
const formData = ref({
  id: '',
  name: '',
  idCard: '',
  phone: '',
  verificationCode: '',
  qq: '',
  education: '',
  school: '',
  emergencyName: '',
  emergencyPhone: '',
  relationship: '',
  bankCard: '',
  bankName: '',
  idCardBack:'',
  idCardFront:'',
 })

// 企业信息
const companyInfo = ref({
  company: '',
  position: '',
  salary: '',
  address: '',
  detailAddress: ''
})



// 选择器数据
const educationOptions = ref<{ id: string, fullName: string }[]>([])
const relationshipOptions = ref<{ id: string, fullName: string }[]>([])

// 选择器索引
const educationIndex = ref(0)
const relationshipIndex = ref(0)

// 验证码倒计时
const countdown = ref(0)
const isCountingDown = ref(false)
const countdownText = computed(() => {
  if (isCountingDown.value && countdown.value > 0) {
    return `${countdown.value}s`
  }
  return '获取验证码'
})

// 选择器显示状态
const showEducationPicker = ref(false)
const showRelationshipPicker = ref(false)

// 获取显示名称的计算属性
const getEducationDisplayName = computed(() => {
  if (!formData.value.education) return ''
  const option = educationOptions.value.find(item => item.id === formData.value.education)
  return option ? option.fullName : ''
})

const getRelationshipDisplayName = computed(() => {
  if (!formData.value.relationship) return ''
  const option = relationshipOptions.value.find(item => item.id === formData.value.relationship)
  return option ? option.fullName : ''
})

// 表单验证
const isFormValid = computed(() => {
  return formData.value.name && 
         formData.value.idCard && 
         formData.value.phone && 
         formData.value.verificationCode &&
         formData.value.education &&
         formData.value.school &&
         formData.value.emergencyName &&
         formData.value.emergencyPhone &&
         formData.value.relationship
})

// 返回
const goBack = () => {
  uni.navigateBack()
}



// 获取验证码
const getVerificationCode = async () => {
  if (!formData.value.phone) {
    uni.showToast({
      title: '请先输入手机号码',
      icon: 'none'
    })
    return
  }
  
  if (isCountingDown.value) {
    return
  }
  
  try {
    const result = await verifyApi.sendVerifyCode(formData.value.phone, 'entry')
    if (result.code === 200) {
      uni.showToast({
        title: '验证码已发送',
        icon: 'success'
      })
      
      // 开始倒计时
      startCountdown()
    } else {
      uni.showToast({
        title: result.msg || '发送失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    uni.showToast({
      title: '发送失败，请重试',
      icon: 'none'
    })
  }
}

// 开始倒计时
const startCountdown = () => {
  isCountingDown.value = true
  countdown.value = 60
  
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
      isCountingDown.value = false
      countdown.value = 0
    }
  }, 1000)
}

// 扫描银行卡
const scanBankCard = async () => {
  try {
    // 调用微信选择图片API
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera', 'album'],
      success: async (res) => {
        const filePath = res.tempFilePaths[0]
        try {
          const result = await verifyApi.ocrBankCard(filePath)
          if (result.code === 200) {
            // 自动填充银行卡信息
            formData.value.bankCard = result.data.bankCardNumber || ''
            formData.value.bankName = result.data.bankName || ''
            uni.showToast({
              title: '银行卡识别成功',
              icon: 'success'
            })
          } else {
            uni.showToast({
              title: result.msg || '识别失败',
              icon: 'none'
            })
          }
        } catch (error) {
          console.error('银行卡识别失败:', error)
          uni.showToast({
            title: '识别失败，请重试',
            icon: 'none'
          })
        }
      },
      fail: (error) => {
        console.error('选择图片失败:', error)
        uni.showToast({
          title: '选择图片失败',
          icon: 'none'
        })
      }
    })
  } catch (error) {
    console.error('扫描银行卡失败:', error)
    uni.showToast({
      title: '扫描失败，请重试',
      icon: 'none'
    })
  }
}

// 学历选择
const onEducationConfirm = (e: any) => {
  const selectedIndex = e.indexs[0]
  const selectedOption = educationOptions.value[selectedIndex]
  formData.value.education = selectedOption.id // 使用id作为值
  showEducationPicker.value = false
}

// 关系选择
const onRelationshipConfirm = (e: any) => {
  const selectedIndex = e.indexs[0]
  const selectedOption = relationshipOptions.value[selectedIndex]
  formData.value.relationship = selectedOption.id // 使用id作为值
  showRelationshipPicker.value = false
}

// 提交表单
const submitForm = async () => {
  if (!isFormValid.value) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
    return
  }
  
  try {
    // 获取用户信息
    const openId = userStore.getOpenId()
    if (!openId) {
      uni.showToast({
        title: '用户未登录',
        icon: 'none'
      })
      return
    }
    
    // 准备提交数据
    const submitData = {
      id: formData.value.id,
      openId: openId,
      name: formData.value.name,
      phone: formData.value.phone,
      idCardNo: formData.value.idCard,
	  idCardBack: formData.value.idCardBack,
	  idCardFront: formData.value.idCardFront,
      code: formData.value.verificationCode,
      weiXin: formData.value.qq, // 使用QQ字段作为微信
      education: formData.value.education,
      schoolName: formData.value.school,
      emergencyName: formData.value.emergencyName,
      emergencyPhone: formData.value.emergencyPhone,
      emergencyRelation: formData.value.relationship,
      bankImageUrl: '', // 银行卡图片URL，需要先上传
      bankNum: formData.value.bankCard,
      bankName: formData.value.bankName,
	  
    }
    
    console.log('提交入职资料数据:', submitData)
    
    const result = await userApi.updateOnboardingData(submitData)
    if (result.code === 200) {
      uni.showToast({
        title: '提交成功',
        icon: 'success'
      })
      
      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      uni.showToast({
        title: result.msg || '提交失败',
        icon: 'none'
      })
         }
   } catch (error) {
     console.error('提交入职资料失败:', error)
     uni.showToast({
       title: '提交失败，请重试',
       icon: 'none'
     })
   }
 }

// 获取数据字典
const fetchDataDictionary = async () => {
  try {
    // 获取学历信息
    const educationResult = await systemApi.getListByTypeDataCode('Education')
    if (educationResult.code === 200 && educationResult.data) {
      educationOptions.value = educationResult.data // 保存完整对象，包含id和fullName
    }
    
    // 获取社会关系
    const relationResult = await systemApi.getListByTypeDataCode('societyRelation')
    if (relationResult.code === 200 && relationResult.data) {
      relationshipOptions.value = relationResult.data // 保存完整对象，包含id和fullName
    }
  } catch (error) {
    console.error('获取数据字典失败:', error)
  }
}

// 获取入职资料信息
const fetchOnboardingData = async () => {
  try {
    const openId = userStore.getOpenId()
    if (!openId) {
      console.log('用户未登录，跳过获取入职资料')
      return
    }
    
    const result = await userApi.getOnboardingData({openId})
    if (result.code === 200 && result.data) {
      const data = result.data
      console.log('接口返回的入职资料数据:', data)
      
      // 将接口返回的数据填入表单
      formData.value.id = data.id || ''
      formData.value.name = data.name || ''
      formData.value.idCard = data.idCardNo || ''
      formData.value.phone = data.phone || ''
      formData.value.qq = data.weiXin || ''
      formData.value.education = data.education || ''
      formData.value.school = data.schoolName || ''
      formData.value.emergencyName = data.emergencyName || ''
      formData.value.emergencyPhone = data.emergencyPhone || ''
      formData.value.relationship = data.emergencyRelation || ''
      formData.value.bankCard = data.bankNum || ''
      formData.value.bankName = data.bankName || ''
      formData.value.idCardBack = data.idCardBack || ''
      formData.value.idCardFront = data.idCardFront || ''
      
 
      
 
      
      console.log('入职资料获取成功，表单已填充:', formData.value)
    }
  } catch (error) {
    console.error('获取入职资料失败:', error)
  }
}

// 获取缓存的最近报名企业信息
const fetchCompanyInfo = () => {
  try {
    const lastSignup = uni.getStorageSync('last_signup')
    if (lastSignup) {
      companyInfo.value = {
        company: lastSignup.company || '',
        position: lastSignup.position || '',
        salary: lastSignup.salary || '',
        address: lastSignup.address || '',
        detailAddress: lastSignup.detailAddress || ''
      }
      console.log('获取缓存的报名企业信息成功:', companyInfo.value)
    }
  } catch (error) {
    console.error('获取缓存的报名企业信息失败:', error)
  }
}

// 页面加载时获取数据字典和入职资料
onMounted(() => {
  fetchDataDictionary()
  fetchOnboardingData()
  fetchCompanyInfo()
})
</script>

<style lang="scss" scoped>
.onboarding-page {
  min-height: 100vh;
  background-color: #F5F5F5;
  padding-bottom: 120rpx;
}

.simple-navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #FFFFFF;
  border-bottom: 1rpx solid #F0F0F0;
  padding-top: calc(20rpx + var(--status-bar-height));
}

.navbar-left {
  width: 60rpx;
}

.back-icon {
  font-size: 36rpx;
  color: #333333;
}

.navbar-title {
  flex: 1;
  text-align: center;
}

.title-text {
  font-size: 36rpx;
  font-weight: 500;
  color: #333333;
}

.navbar-right {
  width: 60rpx;
  text-align: right;
}

.more-icon {
  font-size: 32rpx;
  color: #666666;
}

.welcome-message {
  background-color: #F8F8F8;
  padding: 24rpx 30rpx;
  margin-bottom: 20rpx;
}

.welcome-text {
  font-size: 28rpx;
  color: #666666;
  line-height: 1.4;
}

.section {
  background-color: #FFFFFF;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
  margin-bottom: 24rpx;
}

.company-section {
  padding: 18rpx;
}

.company-card {
  background: linear-gradient(135deg, rgb(255, 228, 204) 0%, rgb(255, 192, 128) 100%);
  border-radius: 16rpx;
  padding: 30rpx;
  position: relative;
  overflow: hidden;
}

.company-status {
  position: relative;
  z-index: 2;
}

.status-text {
  font-size: 28rpx;
  color: rgb(51, 51, 51);
  font-weight: 500;
  display: block;
  margin-bottom: 8rpx;
}

.company-name {
  font-size: 24rpx;
  color: rgb(102, 102, 102);
  display: block;
  margin-bottom: 4rpx;
}

.company-position {
  font-size: 22rpx;
  color: rgb(153, 153, 153);
  display: block;
}

.company-bg {
  position: absolute;
  top: 0;
  right: 0;
  width: 120rpx;
  height: 120rpx;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect x="10" y="20" width="20" height="60" fill="rgba(255,255,255,0.3)"/><rect x="35" y="30" width="20" height="50" fill="rgba(255,255,255,0.3)"/><rect x="60" y="25" width="20" height="55" fill="rgba(255,255,255,0.3)"/><rect x="85" y="35" width="10" height="45" fill="rgba(255,255,255,0.3)"/></svg>') no-repeat center;
  background-size: contain;
  opacity: 0.6;
}

.form-container {
  background-color: #FFFFFF;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #F0F0F0;
  
  &:last-child {
    border-bottom: none;
  }
}

.form-label {
  display: flex;
  align-items: center;
  min-width: 200rpx;
  flex-shrink: 0;
}

.required {
  color: #FF4757;
  font-size: 28rpx;
  margin-right: 4rpx;
}

.label-text {
  font-size: 28rpx;
  color: #333333;
}

.label-desc {
  font-size: 24rpx;
  color: #999999;
  margin-left: 8rpx;
}

.form-input {
  flex: 1;
  font-size: 28rpx;
  color: #333333;
  background-color: transparent;
  border: none;
  outline: none;
  
  &.disabled {
    color: #999999;
  }
}

.upload-container {
  flex: 1;
}

.phone-input {
  display: flex;
  align-items: center;
  gap: 16rpx;
  flex: 1;
}

/* 验证码按钮样式已通过u-button的customStyle设置 */

.bank-input {
  display: flex;
  align-items: center;
  gap: 16rpx;
  flex: 1;
}

.camera-icon {
  font-size: 24rpx;
  color: #999999;
}

.select-input {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex: 1;
  padding: 0;
}

.select-text {
  font-size: 28rpx;
  color: #333333;
  
  &.placeholder {
    color: #999999;
  }
}

.arrow-icon {
  font-size: 20rpx;
  color: #999999;
}

.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #FFFFFF;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid #F0F0F0;
  z-index: 999;
}

/* 提交按钮样式已通过u-button的customStyle设置 */
</style> 